package com.wmapp.utils;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

public abstract class HttpUtils {
	private static Log log=LogFactory.getLog(HttpUtils.class);
	public static final String OPT_TYPE_NEW="new";
	public static final String OPT_TYPE_MODIFY="modify";
	
	//{rows:[{id:"",data:["",""]},{id:"",data:["",""]}]}
	public static JSONObject domainList2GridRecords(List data,Class clazz,String[] propertyNames,String idName){
		JSONObject ret=new JSONObject();
		
		try {
			JSONArray jArray=new JSONArray();
			for (Iterator iterator = data.iterator(); iterator.hasNext();) {
				Object obj = (Object) iterator.next();
				JSONObject jObj=new JSONObject();
				Method getIdMethod = clazz.getMethod(SimpleStringUtils.join("get",StringUtils.capitalize(idName)), null);
				
				jObj.put("id", getIdMethod.invoke(obj, null));
				
				Object[] propValues=new Object[propertyNames.length];
				for (int i = 0; i < propertyNames.length; i++) {
					Method getMethod=clazz.getMethod(SimpleStringUtils.join("get",StringUtils.capitalize(propertyNames[i])), null);
					propValues[i]=getMethod.invoke(obj, null);
				}
				
				jObj.put("data", propValues);
				
				jArray.add(jObj);
			}
			ret.put("rows", jArray);
		} catch (Exception e) {
			log.error("doamin list 2 json array fail.", e);
		}
		
		return ret;
	}

    //[{attr1:"val1",att2:"val2"},...]
	public static JSONArray domainList2ChartJson(List data,Class clazz,String[] propertyNames){
        JSONArray jArray=new JSONArray();
		try {
			
			for (Iterator iterator = data.iterator(); iterator.hasNext();) {
				Object obj = (Object) iterator.next();
				JSONObject jObj=new JSONObject();			

				Object[] propValues=new Object[propertyNames.length];
				for (int i = 0; i < propertyNames.length; i++) {
					Method getMethod=clazz.getMethod(SimpleStringUtils.join("get",StringUtils.capitalize(propertyNames[i])), null);
                    propValues[i]=getMethod.invoke(obj, null);
                    jObj.put(propertyNames[i], propValues[i]);
                }

				jArray.add(jObj);
			}
		} catch (Exception e) {
			log.error("doamin list 2 json array fail.", e);
		}
		return jArray;
	}
}
